<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2017/1/23
 * Time: 上午12:06
 */

namespace Conf;


use App\Model\Putter;
use App\Model\Queue;
use Core\AbstractInterface\AbstractEvent;
use Core\Http\Request;
use Core\Http\Response;
use Core\Component\ShareMemory;
use App\Utility\SysConst;
use App\Model\Runner;
use Core\Swoole\AsyncTaskManager;
use Core\Swoole\Timer;
use Core\Component\Logger;
use Core\AutoLoader;
use Core\Component\Di;


class Event extends AbstractEvent
{
    function frameInitialize()
    {
        // TODO: Implement frameInitialize() method.
        date_default_timezone_set('Asia/Shanghai');
        AutoLoader::getInstance()->requireFile("Core/Vendor/Db/MysqliDb.php");
        $conf = Config::getInstance()->getConf('MYSQL');
        Di::getInstance()->set(SysConst::MYSQL,\MysqliDb::class,$conf['HOST'],$conf['USER'],$conf['PASSWORD'],$conf['DB_NAME']);
        ShareMemory::getInstance()->clear();
    }

    function frameInitialized()
    {
        // TODO: Implement frameInitialized() method.
    }


    function beforeWorkerStart(\swoole_server $server)
    {
    }

    function onStart(\swoole_server $server)
    {
        global $argv;
        swoole_set_process_name('php ' . $argv[0] . ': master ');
    }

    function onShutdown(\swoole_server $server)
    {
        // TODO: Implement onShutdown() method.
    }

    function onWorkerStart(\swoole_server $server, $workerId)
    {
        global $argv;
        if ($workerId >= $server->setting['worker_num']) {
            swoole_set_process_name('php ' . $argv[0] . ': task');
        } else {
            swoole_set_process_name('php ' . $argv[0] . ': worker');
        }

        if($workerId == 0) {
            Timer::loop(1000,function (){
                $share = ShareMemory::getInstance();
                if($share->get(SysConst::TASK_RUNNING_NUM) <= 10){
                    AsyncTaskManager::getInstance()->add(Runner::class);
                }
            });

            Timer::loop(2000,function (){
                Putter::put();
            });

            Timer::loop(60000,function (){
                Putter::unlock();
            });
        }
    }

    function onWorkerStop(\swoole_server $server, $workerId)
    {
        // TODO: Implement onWorkerStop() method.
    }

    function onRequest(Request $request, Response $response)
    {
    }

    function onDispatcher(Request $request, Response $response, $targetControllerClass, $targetAction)
    {
        // TODO: Implement onDispatcher() method.
    }

    function onResponse(Request $request,Response $response)
    {
        // TODO: Implement afterResponse() method.
    }

    function onTask(\swoole_server $server, $taskId, $workerId, $taskObj)
    {

    }

    function onFinish(\swoole_server $server, $taskId, $taskObj)
    {

    }

    function onWorkerError(\swoole_server $server, $worker_id, $worker_pid, $exit_code)
    {

    }
}
